import 'dart:collection';
import 'package:stock_check/common/config/Config.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:dio/dio.dart';
import 'package:stock_check/common/http/Api.dart';

class HttpManager{
  static const CONTENT_TYPE_JSON = 'application/json';
  static const CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded';
  static Map optionParams = {
    "timeoutMs": 15000,
    "token": null,
    "authorizationCode": null,
  };

  ///发起网络请求
  ///[ url] 请求url
  ///[ params] 请求参数
  ///[ header] 外加头
  ///[ option] 配置
  static netFetch(url,Map<String,dynamic> params,{Map<String,String> header,Options option}) async {
    Map<String,String> headers = new HashMap();
    if(header!=null){
      headers.addAll(header);
    }

    if(option == null){
      option = new Options(
          method: 'get',
          baseUrl: Api.baseUrl
      );
    }else{
      option.baseUrl = Api.baseUrl;
    }

    Dio dio = new Dio();
    Response response;

    try{
      response = await dio.request(url,data: params,options: option);
      return new DataResult(response.data, true);
    } on DioError catch (e) {
      Response error;
      if(e.response != null){
        error = e.response;
      } else {
        error = new Response(statusCode: 666);
      }
      if(e.type == DioErrorType.CONNECT_TIMEOUT){
        error.statusCode = -1; // 超时
      }
      if(Config.DEBUG_MODE){
        print('请求异常' + e.toString());
        print('请求异常URL'+ url);
      }
      return new DataResult(error,false);
    }
  }


}